package com.example.tech.folio.interceptor;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class SessionInterceptor implements HandlerInterceptor {

    public static final String ACCEPT_HTML_PREFIX = "text/html";
    public static final String ACCEPT_JSON_PREFIX = "application/json";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("admin");
        if (user == null) {
            response.setCharacterEncoding("UTF-8");
            String accept = request.getHeader("accept");
            if (accept.startsWith(ACCEPT_HTML_PREFIX)) {
                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                response.setHeader("Location", "/");
            } else if (accept.startsWith(ACCEPT_JSON_PREFIX)) {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(errorJson);
                writer.close();
            } else {
                throw new ServletException("服务器正在维护中，请稍后再试");
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private static String errorJson = "{\n" +
            "    \"code\": 40100,\n" +
            "    \"message\": \"无登录信息，可能已过期，请登录！\"\n" +
            "}";

}
